24. Exercise: Data Messages
L1 A24 Data Messages
Exercise
- In order to handle FCM messages, you need to handle the data payload in the
onMessageReceived()function ofMyFirebaseMessagingService. The data payload is stored in the data property of theremoteMessageobject. BothremoteMessageobject and the data property can benull. Check if data property ofremoteMessageobject has some value and print the data to the log.
- Add a log to print data property of the
remoteMessageobject after checkingremoteMessageand data is not empty.
// MyFirebaseMessagingService.kt
// [START receive_message]
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
// Not getting messages here? See why this may be: https://goo.gl/39bRNJ
Log.d(TAG, "From: ${remoteMessage?.from}")
// TODO: Step 3.5 check messages for data
// Check if message contains a data payload.
remoteMessage?.data?.let {
Log.d(TAG, "Message data payload: " + remoteMessage.data)
}
}
// [END receive_message]
- To test your code, you can use the Notifications composer again, this time setting Custom data key, value pairs under Additional options in Step 4. Create a new message and select the same topic. Set eggs and 3 as custom data.
- Make sure your app is running and in foreground. Send the message and observe data message log in the
logcat.
If your app is in the background, the FCM message will trigger an automatic notification and onMessageReceived function will receive the remoteMessage object only when the user clicks the notification.